/*********************************************************
*Copyright (c) 2015 zhongsx. All Rights in Pw 
*@des: 环型缓冲区 
*@name: CircleBuffer.h
*@author: zhongsx
*@time: 2015-03-07
*********************************************************/
#ifndef __CIRCLE_BUFFER_H__
#define __CIRCLE_BUFFER_H__

#include <stdio.h>
#include <stdlib.h>
#include <boost/thread/mutex.hpp>
//#include <boost/thread/recursive_mutex.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/thread/condition_variable.hpp>


/*
 * 环形队列 用条件变量实现N:M 生产者：消费者 同步 
 */
template<typename T>
class CircleQueue {
private:
	boost::circular_buffer<T> 	queue_;
    int max_size; //buffer 最大容量

	//条件变量 
	boost::condition_variable_any 	variable_;
	mutable boost::mutex   mutex_;
public:
	CircleQueue(int queue_size = 10240) :max_size(queue_size)
	{
		queue_ = boost::circular_buffer<T>(max_size);
	}

	~CircleBuffer(){
		
	}
 
	bool write(T& node){
		boost::mutex::scoped_lock lock(mutex_);

		int num = queue_.size();
		if (num >= max_size){
			lock.unlock();
			_variable.notify_all();
			//数据队列满，再次唤醒线程
			return false;
		}
		queue_.push_back(node);
		lock.unlock();
		_variable.notify_all();
		return true;
	}

	T& read(){
		boost::mutex::scoped_lock lock(mutex_);

		int num = queue_.size();
		while (0 == num){
			_variable.wait(lock);
			num = queue_.size();
		}

		T& node = _queue.front();
		_queue.pop_front();
		return node;
	}
	
};
 
#endif //__CIRCLE_BUFFER_H__